using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.Polls
{
    [Serializable()]
    public class PollResultsDetail : Csla.BusinessBase<PollResultsDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _pollId = Guid.Empty;
        private Guid _pollChoice = Guid.Empty;
        private Guid _userid = Guid.Empty;

        [System.ComponentModel.DataObjectField(true, false)]
        public Guid PollId
        {
            get
            {
                CanReadProperty("PollId", true);
                return _pollId;
            }
            set
            {
                CanWriteProperty("PollId", true);
                if (!_pollId.Equals(value))
                {
                    _pollId = value;
                    PropertyHasChanged("PollId");
                }
            }
        }

        public Guid PollChoice
        {
            get
            {
                CanReadProperty("PollChoice", true);
                return _pollChoice;
            }
            set
            {
                CanWriteProperty("PollChoice", true);
                if (!_pollChoice.Equals(value))
                {
                    _pollChoice = value;
                    PropertyHasChanged("PollChoice");
                }
            }
        }

        [System.ComponentModel.DataObjectField(true, false)]
        public Guid Userid
        {
            get
            {
                CanReadProperty("Userid", true);
                return _userid;
            }
            set
            {
                CanWriteProperty("Userid", true);
                if (!_userid.Equals(value))
                {
                    _userid = value;
                    PropertyHasChanged("Userid");
                }
            }
        }

        protected override object GetIdValue()
        {
            return string.Format("{0}:{1}", _pollId, _userid);
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {

        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in PollResultsDetail
            //AuthorizationRules.AllowRead("PollId", "PollResultsDetailReadGroup");
            //AuthorizationRules.AllowRead("PollChoice", "PollResultsDetailReadGroup");
            //AuthorizationRules.AllowRead("Userid", "PollResultsDetailReadGroup");

            //AuthorizationRules.AllowWrite("PollChoice", "PollResultsDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in PollResultsDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PollResultsDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in PollResultsDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PollResultsDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in PollResultsDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PollResultsDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in PollResultsDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PollResultsDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private PollResultsDetail()
        { /* require use of factory method */
        }

        public static PollResultsDetail NewPollResultsDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a PollResultsDetail");
            return DataPortal.Create<PollResultsDetail>(new Criteria());
        }

        public static PollResultsDetail GetPollResultsDetail(Guid pollId, Guid userid)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a PollResultsDetail");
            return DataPortal.Fetch<PollResultsDetail>(new Criteria(pollId, userid));
        }

        public static void DeletePollResultsDetail(Guid pollId, Guid userid)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a PollResultsDetail");
            DataPortal.Delete(new Criteria(pollId, userid));
        }

        public override PollResultsDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a PollResultsDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a PollResultsDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a PollResultsDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid PollId;
            public Guid Userid;

            public Criteria()
            {
            }

            public Criteria(Guid pollId, Guid userid)
            {
                this.PollId = pollId;
                this.Userid = userid;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        private void DataPortal_Create(Criteria criteria)
        {
            _pollId = criteria.PollId;
            _userid = criteria.Userid;
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@PollId", criteria.PollId);

            using (SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader("usp_get_poll_result_bypollid", CommandType.StoredProcedure, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _pollId = dr.GetGuid("PollId");
            _pollChoice = dr.GetGuid("PollChoice");
            _userid = dr.GetGuid("userid");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertPollResult.ToString().Trim(), CommandType.Text, ConnectionState.Open);

            UpdateAnswerCountOnInsert();
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@PollId", _pollId);
            DAL.AddParameter("@PollChoice", _pollChoice);
            DAL.AddParameter("@userid", _userid);
        }

        private void UpdateAnswerCountOnInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@PollId", _pollId);
            DAL.AddParameter("@AnswerId", _pollChoice);

            DAL.ExecuteNonQuery(Procs.UpdateVoteCountOnResultInsert.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery("usp_update_poll_result", CommandType.StoredProcedure, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@PollId", _pollId);
            DAL.AddParameter("@PollChoice", _pollChoice);
            DAL.AddParameter("@userid", _userid);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_pollId, _userid));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery("usp_delete_poll_result", CommandType.StoredProcedure, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@pollid", criteria.PollId);
            DAL.AddParameter("@userid", criteria.Userid);
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
